// task_pay_page.dart
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:sjx/pages/task/pay/task_pay_vm.dart';
import 'package:fluwx/fluwx.dart';

class TaskPayPage extends StatefulWidget {
  final VoidCallback? refreshHandle;
  final String taskId;
  final String amountStr;
  final bool isAddTask;
  final int addDays;
  final int addCount;

  const TaskPayPage({
    Key? key,
    this.refreshHandle,
    required this.taskId,
    required this.amountStr,
    this.isAddTask = false,
    this.addDays = 0,
    this.addCount = 0,
  }) : super(key: key);

  @override
  _TaskPayPageState createState() => _TaskPayPageState();
}

class _TaskPayPageState extends State<TaskPayPage> {
  late final TaskPayViewModel _viewModel = TaskPayViewModel(refreshHandle: widget.refreshHandle);

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_){
      _viewModel.initWechatPay(context);
    });
    _viewModel.priceAmount(widget.amountStr);
    _viewModel.getAccount();
  }

  @override
  void dispose() {
    _viewModel.cancelSub(); // 务必取消订阅，防止内存泄漏
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (context) {
      return _viewModel;
    },
      child: Consumer<TaskPayViewModel>(builder: (context, value, child) {
        return Scaffold(
          backgroundColor: Color(0xFFF5F8FA),
          appBar: AppBar(
            title: Text('付款'),
            backgroundColor: Colors.white,
            foregroundColor: Colors.black,
            elevation: 0.5,
            leading: IconButton(
              icon: Icon(Icons.arrow_back_ios),
              onPressed: () => Navigator.pop(context),
            ),
          ),
          body: value.isLoading ? _buildLoadingView() : _buildContentView(value),
          bottomNavigationBar: _buildPayButton(value),
        );
      }),
    );
  }

  Widget _buildLoadingView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(),
          SizedBox(height: 16),
          Text('正在加载...'),
        ],
      ),
    );
  }

  Widget _buildContentView(TaskPayViewModel viewModel) {
    return SingleChildScrollView(
      child: Column(
        children: [
          _buildNoticeBanner(),
          _buildAmountSection(viewModel),
          _buildBalanceSection(viewModel),
          _buildPaymentMethodSection(viewModel),
        ],
      ),
    );
  }

  Widget _buildNoticeBanner() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(12),
      color: Color(0xFFFFF5EB),
      child: Text(
        '任务结束后，任务仍有余额，系统将自动退回至平台账户。',
        style: TextStyle(
          fontSize: 13,
          color: Color(0xFFFFB02E),
        ),
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget _buildAmountSection(TaskPayViewModel viewModel) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 20),
      color: Colors.white,
      width: double.maxFinite,
      child: Column(
        children: [
          Text(
            '付款金额',
            style: TextStyle(
              fontSize: 13,
              color: Colors.grey[600],
            ),
          ),
          SizedBox(height: 8),
          Text(
            '￥${viewModel.actualAmount.toStringAsFixed(2)}',
            style: TextStyle(
              fontSize: 30,
              fontWeight: FontWeight.bold,
              color: Color(0xFF2D2D2D),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBalanceSection(TaskPayViewModel viewModel) {
    return Container(
      margin: EdgeInsets.only(top: 1),
      padding: EdgeInsets.symmetric(horizontal: 15, vertical: 12),
      color: Colors.white,
      child: Row(
        children: [
          Icon(
            Icons.account_balance_wallet,
            size: 19,
            color: Colors.grey[700],
          ),
          SizedBox(width: 8),
          Expanded(
            child: Text(
              '余额：￥${viewModel.availableAmount.toStringAsFixed(2)}',
              style: TextStyle(
                fontSize: 13,
                color: Color(0xFF2D2D2D),
              ),
            ),
          ),
          _buildDeductButton('不抵扣', viewModel.isNotDeductSelected, viewModel.onNotDeductSelected),
          SizedBox(width: 8),
          _buildDeductButton(
            ' 抵扣￥${viewModel.deductAmount.toStringAsFixed(2)}',
            viewModel.isDeductSelected,
            viewModel.onDeductSelected,
          ),
        ],
      ),
    );
  }

  Widget _buildDeductButton(String text, bool isSelected, VoidCallback onPressed) {
    return GestureDetector(
      onTap: onPressed,
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 8, vertical: 6),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
              size: 16,
              color: isSelected ? Theme.of(context).primaryColor : Colors.grey,
            ),
            SizedBox(width: 4),
            Text(
              text,
              style: TextStyle(
                fontSize: 13,
                color: Color(0xFF2D2D2D),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildPaymentMethodSection(TaskPayViewModel viewModel) {
    return Container(
      margin: EdgeInsets.only(top: 12),
      color: Colors.white,
      child: Column(
        children: [
          _buildPaymentMethodItem(
            '支付宝支付',
            'assets/images/zhifubao_icon.png',
            viewModel.isAlipaySelected,
            viewModel.onAlipaySelected,
          ),
          Divider(height: 1),
          _buildPaymentMethodItem(
            '微信支付',
            'assets/images/weixin_icon.png',
            viewModel.isWechatSelected,
            viewModel.onWechatSelected,
          ),
        ],
      ),
    );
  }

  Widget _buildPaymentMethodItem(
      String title, String iconPath, bool isSelected, VoidCallback onTap) {
    return ListTile(
      leading: Image.asset(
        iconPath,
        width: 18,
        height: 18,
      ),
      title: Text(
        title,
        style: TextStyle(
          fontSize: 13,
          color: Color(0xFF5F5F5F),
        ),
      ),
      trailing: Icon(
        isSelected ? Icons.radio_button_checked : Icons.radio_button_unchecked,
        color: isSelected ? Theme.of(context).primaryColor : Colors.grey,
      ),
      onTap: onTap,
    );
  }

  Widget _buildPayButton(TaskPayViewModel viewModel) {
    return Container(
      height: 44 + MediaQuery.of(context).padding.bottom,
      padding: EdgeInsets.only(
        bottom: MediaQuery.of(context).padding.bottom,
      ),
      child: ElevatedButton(
        onPressed: viewModel.isLoading ? null : () => viewModel.onPayPressed(context, widget.taskId),
        style: ElevatedButton.styleFrom(
          backgroundColor: Theme.of(context).primaryColor,
          foregroundColor: Colors.white,
          shape: RoundedRectangleBorder(),
          elevation: 0,
        ),
        child: viewModel.isLoading
            ? SizedBox(
          height: 20,
          width: 20,
          child: CircularProgressIndicator(
            strokeWidth: 2,
            valueColor: AlwaysStoppedAnimation(Colors.white),
          ),
        )
            : Text(
          '支付',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.w500,
          ),
        ),
      ),
    );
  }
}